import axios from 'axios'
import ElMessage from 'element-plus'
//设置全局的axios的配置
const service = axios.create({
	baseURL: '/',
	timeout: 100000,
})

/*配置请求的拦截*/
service.interceptors.request.use(
	function (config) {
		const headers = config.headers
		//后期会补充token
		return config
	},
	function (error) {
		return Promise.reject(error)
	}
)

/*定义响应拦截*/
service.interceptors.response.use(
	(response) => {
		if (response.status === 200) {
			const { message, code, data } = response
			console.log(response)
			return data
		}
		//解构赋值，从data中解构出需要的数据字段
	},
	(error) => {
		console.log(error)
		setTimeout(() => {
			ElMessage.error('结果返回超时')
		}, 1500)
		return Promise.reject(error)
	}
)

//request({method:'post',url:"/user/list",data:[id:1]])
//request({method:'Get',url:"/user/list",data:[id:1}})
function request(options) {
	//定义提交的方式,默认为get
	options.method = options.method || 'get'
	if (options.method.toLowerCase() === 'get') {
		options.params = options.data
	}
	return service(options)
}
//封装get,post,put   request.get(url,data,options)request.post(url,data,options)
;['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
	request[item] = (url, data, options) => {
		return request({ method: item, url, data, ...options })
	}
})
export default request
